import React, { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { AtModal } from 'taro-ui';
import {View,Image,Text, Canvas, Swiper, SwiperItem} from '@tarojs/components'
import YiCode from '@/components/yi-code'
import "taro-ui/dist/style/components/modal.scss";
import './index.scss'

export default function OpenCard() {
  const [info, setinfo] = useState({})
  const [list, setList] = useState([])
  const [curSelect,setCurSelect] = useState(0)
  const [isAgree,setIsAgree] = useState(false)
  const [showModal,setShowModal] = useState(false)
  const [captcha,setCaptcha] = useState('')
  const [messageInfo,setMessageInfo] = useState('')
  useEffect(()=>{
    const {router} = Taro.getCurrentInstance()
    Taro.showLoading({title:'加载中...'})
    Taro.$post(`/cinema-app/api/card/getMyGiftCardInfo`,{
      "id": router.params.id,
      "type": router.params.isDxCard
    }).then(res=>{
      if(res.code == '1'){
        setinfo(res.content)
      }else{
        Taro.$toast(res.message)
      }
    })
    Taro.$get(`/cinema-app/api/rechargePackage`,{
      cardId:router.params.id,
      cinemaId:Taro.getStorageSync('merchantId')
    },'1').then(res=>{
      if(res.code == '1'){
        setList(res.content)
      }
    })
  },[])
  const handlePay =(content,orderId)=>{
    if(process.env.TARO_ENV == 'tt'){
      tt.pay({
        orderInfo: {
          order_id:content.data.orderId,
          order_token: content.data.orderToken
        },
        service: 5,
        _debug:1,
        success:res=>{
          if(res.code == 0){
            Taro.navigateBack()
          }
        },
        fail:err=>{
          Taro.$toast('支付失败')
        }
      });
      return;
    }
    if(process.env.TARO_ENV == 'h5' && navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger"){
      WeixinJSBridge.invoke('getBrandWCPayRequest', {
        "appId": Taro.$mpAppid,
        "timeStamp": content.timeStamp,   
        "nonceStr": content.nonceStr,  
        "package": content.packageStr,
        "signType": content.signType,    
        "paySign":content.paySign
      },(result) => {
        if(result.err_msg == "get_brand_wcpay_request:cancel"){
          Taro.$toast('取消支付','error')
        }else{
          Taro.navigateBack()
        }
      });
      return;
    }
    Taro.requestPayment({
      timeStamp: content.timeStamp,
      nonceStr: content.nonceStr,
      package: content.package,
      signType: content.signType,
      paySign: content.paySign,
      success:res=>{
        Taro.navigateBack()
      },
      fail:err=>{
        Taro.$toast('支付失败')
      }
    })
  }
  return (
    <View className='page-open-card'>
      <View className="card-header" style={{background:info.backgroundContent?.includes('http')?`url(${info.backgroundContent})`:info.backgroundContent}}>
        <View className="item-icon">开卡特惠</View>
        <View className="item-header">
          <Image className='header-img' src={Taro.getStorageSync('appConfig')?.iconUrl || require('@/images/mine/logo.png')} mode='aspectFill'></Image>
          {info.cardName}
        </View>
        <View className="item-desc">
          <View className="desc-p">{info.typeDesc} <Text style={{fontSize:'12PX',opacity:.8}} className='dot'>{info.explain}</Text></View>
          <View></View>
        </View>
      </View>
      <View className="card-select">
        <View className="card-h2">选择充值面额 <Text className='h2-span'>（不同充值档位赠送不同礼品）</Text></View>
        <View className="select-list">
          {list?.map((res,index)=>{
            return <View key={index} className={`list-item ${curSelect == index?'active':''}`} onClick={()=>{setCurSelect(index)}}>
              <View className="item-h2">{res.packageMoney}元</View>
              到账{res.packageMoney}元
            </View>
          })}
        </View>
      </View>
      {list[curSelect]?.couponList && list[curSelect].couponList?.length?
      <View className="card-gift">
        <View className="card-h2">赠送礼品</View>
        <View className="gift-list">
          {list[curSelect].couponList.map((res)=>{
            return <View key={res.id} className="list-item">
              <View className="item-header">
                <View className="header-info">
                  <View className="info-h2 dot2">{res.couponTypeDesc?<Text className='h2-span'>{res.couponTypeDesc}</Text>:null}{res.couponName}</View>
                  {res.effectEndDate?<View className="info-p">有效期至 {res.effectEndDate}</View>:null}
                </View>
                <View className="header-price">
                  <View className="price-info"><Text style={{fontSize:10,fontWeight:400}}>￥</Text>{res.couponFace}</View>
                  {res.threshold == '有门槛'?res.thresholdValue*1>0?`满${res.thresholdValue}减${res.couponFace}`:'':'无门槛'}
                </View>
              </View>
              <View className="item-footer">
                {res.couponInfo || ' '}
                <View className="footer-button">赠送 {res.giveAmount} 张</View>
              </View>
            </View>
          })}
        </View>
      </View>:null}

      <View className="card-footer">
        <View className="footer-agree">
          {isAgree?<Image onClick={()=>{
            setIsAgree(false)
          }} className='agree-img' src={require('@/images/mine/radio-on.svg')}></Image>:<Image onClick={()=>{
            setIsAgree(true)
          }} className='agree-img' src={require('@/images/mine/radio.svg')}></Image>}
          已阅读并同意<Text onClick={()=>{
            
          }}>《电影卡充值协议》</Text>
        </View>
        <View className="footer-button" onClick={()=>{
          if(!isAgree){
            Taro.showToast({
              title:'请先已阅读并同意电影卡充值协议',
              icon:'none'
            })
            return
          }
          if(!list.length) return;
          Taro.showModal({
            title:"立即充值",
            content:"是否立即充值?",
            success:result=>{
              if(result.confirm){
                Taro.$post('/cinema-app/api/dx/card/cardRecharge',{
                  "cardId": info.id,
                  "rechargePackageId":list[curSelect]?.id,
                }).then(async res=>{
                  if(res.code == '1'){
                    Taro.showLoading({title:'加载中...'})
                    Taro.$post('/order/users/orders/pay',{
                      "appId": Taro.$mpAppid,
                      "channelType": "WXPAY",
                      "openId": await Taro.getOpenId(),
                      "orderId": res.content.orderId
                    },'1').then(ret=>{
                      if(res.code == '1'){
                        setShowModal(false)
                        handlePay(ret.content,res.content.orderId)
                      }
                    })
                  }else{
                    setMessageInfo(res.message || '充值失败')
                  }
                })
              }
            }
          })
        }}>立即充值</View>
      </View>

    </View>
  )
}
